package com.hengshan.controller;


import com.alibaba.fastjson2.JSONObject;
import com.hengshan.common.annotation.SystemLog;
import com.hengshan.common.enums.BusinessType;
import com.hengshan.domain.entity.Menu;
import com.hengshan.service.impl.MenuServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限表(Menu)表控制层
 *
 * @author muxijun
 * @since 2023-12-22 15:42:58
 */
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/system/menu")
public class MenuController {

    private final MenuServiceImpl menuService;
    public static final String MODULE_NAME = "菜单管理";

    @SystemLog(title = MODULE_NAME, businessType = BusinessType.INSERT)
    @PostMapping({"/add"})
    public Menu add(@Validated @RequestBody Menu menu) {
        return menuService.add(menu);
    }

    @SystemLog(title = MODULE_NAME, businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public Menu update(@Validated @RequestBody Menu menu) {
        return menuService.update(menu);
    }

    @SystemLog(title = MODULE_NAME, businessType = BusinessType.DELETE)
    @GetMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") List<Integer> ids) {
        return menuService.deleteByIds(ids);
    }

    @GetMapping("/list")
    public List<Menu> list(@RequestParam(required = false) String name,@RequestParam(required = false) Integer status) {
        return menuService.getList(name,status);
    }

    @GetMapping(value = {"/info/{id}", "/{id}"})
    public Menu getInfo(@PathVariable(value = "id") Integer id) {
        return menuService.getOneById(id);
    }

    /**
     * 获取菜单树
     */
    @RequestMapping("/menuTreeSelect")
    public List<Menu> menuTreeSelect() {
        // 获取所有菜单
        List<Menu> allMenus = menuService.selectAllMenus();
        // 提取构建菜单树的字段
        List<Menu> menus = allMenus.stream().map(e -> new Menu(e.getId(), e.getName(), e.getParentId())).collect(Collectors.toList());
        return menuService.builderMenuTree(menus);
    }

    /**
     * 加载对应角色菜单树
     */
    @GetMapping(value = "/roleMenuTreeSelect/{roleId}")
    public JSONObject roleMenuTreeSelect(@PathVariable("roleId") Integer roleId) {
        JSONObject res = new JSONObject();
        res.put("menus", menuTreeSelect());
        res.put("checkedKeys", menuService.selectMenuIdsByRoleId(roleId));
        return res;
    }
}

